package cn.frontop.funswitch.config.web;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.frontop.funswitch.config.web.ServiceContext.REQUEST_ID;

/**
 * 服务上下文拦截器
 *
 * @author Yun
 */
@Slf4j
@Configuration
public class ServiceContextInterceptor implements WebMvcConfigurer {

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request,
                                     HttpServletResponse response, Object handler) {
                String requestId = IdUtil.simpleUUID();
                MDC.put(REQUEST_ID, requestId);
                ServiceContext.setRequestId(requestId);
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
                //销毁请求id
                ServiceContext.clearAll();
                MDC.clear();
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}

